<?php
namespace Ayhome\Suite\Command;

use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use think\facade\Config;
use think\facade\Env;

use swoole_process;
class Crontab extends Command
{
  protected $config = [];
  public function configure()
  {
    $this->setName('crontab')
        ->addArgument('action', Argument::OPTIONAL, "start|stop|restart|reload", 'start')
        ->addOption('daemon', 'd', Option::VALUE_NONE, 'Run the swoole server in daemon mode.')
        ->setDescription('Swoole Process for ThinkPHP');
  }

  public function execute(Input $input, Output $output)
  {
    $action = $input->getArgument('action');
    $this->config = config('crontab.');

    if ($this->input->hasOption('daemon')) {
      $this->config['daemonize'] = true;
    }

    if (empty($this->config['pid_file'])) {
      $this->config['pid_file'] = Env::get('runtime_path') . 'suite-crontab.pid';
    }

    if (in_array($action, ['start', 'stop'])) {
        $this->$action();
    } else {
        $output->writeln("<error>Invalid argument action:{$action}, Expected start|stop .</error>");
    }
  }

  public function start()
  {

    $pidFile = $this->config['pid_file'];

    if (file_exists($pidFile)) {
      $this->output->writeln('<error>suite crontab process is already running.</error>');
      return false;
    }

    if ($this->config['database']) {
      $tasks = db($this->config['database'])->select();
      $this->config['tasks'] = $tasks;
    }


    $Crontab = new \Ayhome\Suite\Process\Crontab('suite:crontab');
    if ($this->config['daemonize']) {
      $Crontab->daemon();
    }
    
    $Crontab->config = $this->config;


    $pid = $Crontab->start();
    file_put_contents($pidFile, $pid);


    $Crontab->wait(function ($ret) {
      unlink($pidFile);
    });
    return;
  }


  public function stop()
  {
    $pidFile = $this->config['pid_file'];
    if (is_file($pidFile)) {
      $pid = (int) file_get_contents($pidFile);
      swoole_process::kill($pid, SIGTERM);
      unlink($pidFile);
    } else {
      $pid = 0;
    }

    return;

  }

}
